package org.bing.engine.console.service;

import java.net.InetAddress;
import java.util.Date;

import org.bing.engine.common.logging.Log;
import org.bing.engine.common.logging.LogFactory;
import org.bing.engine.common.multicast.AbstractHandler;
import org.bing.engine.common.multicast.MulticastServer;
import org.bing.engine.core.domain.Controller;

public class MulticastManager {
    private static final Log logger = LogFactory.getLog(MulticastManager.class); 
    private ControllerManager ctlMgr;
    private MulticastServer server;

    public void setControllerManager(ControllerManager mgr) {
        this.ctlMgr = mgr;
    }

    public void setServer(MulticastServer server) {
        this.server = server;
    }

    public void start() {
        server.addHandler(new AbstractHandler() {
            @Override
            public void handle(InetAddress addr, String msg) {
                // TODO L3, impl security, multicast storm
                logger.info("HostName:" + addr.getHostName() + ", Address:" + addr.getHostAddress() + ", " + msg);
                Controller c = (Controller) codec.decode(msg);
                if (c != null) { 
                    c.setAddress(addr.getHostAddress());
                    c.setHostname(addr.getHostName());
                    if(c.getLastActivityTime()==null){
                        c.setLastActivityTime(new Date());
                    } 
                    ctlMgr.multicast(c);
                }
            }
        });
        Thread t = new Thread() {
            public void run() {
                logger.info("Start multicast server " + server.getMulticastIp() + ":" + server.getMulticastPort() + " ...");
                server.start();
            }
        };
        t.setName("bing-multicast-server");
        t.start();
    }

    public void stop() {
        server.shutdown();
    }

    public static void main(String[] args) {
        new MulticastManager().start();
        // mm.start();
        // boolean flag = (null instanceof java.util.Date);
        // System.out.println(flag);
    }
}
